'use strict';

angular.module('oaApp')
  .controller('SharesCtrl', function ($scope, $http, $upload, Auth, socket) {
    $scope.shares = [];
    $scope.progress = false;
    $scope.nowProgress = 0;
    $scope.progressStatus = '';
    $scope.currentUser = Auth.getCurrentUser();
    console.log(Auth.getCurrentUser());

    $http.get('/api/shares')
      .success(function (res) {
        $scope.shares = res;
        socket.syncUpdates('share', $scope.shares);
      })
      .error(function (err) {
        console.log('获取文件共享失败');
      });

    $scope.removeFile = function(id, idx) {
      if(confirm('你确定删除该文件吗？')){
        $http.delete('/api/shares/'+id).success(function () {
          console.log('删除成功');
          $scope.shares.splice(idx, 1);
        }).error(function () {
          console.log('删除失败');
        });
      }
    };

    var currentProject = {
      user: {
        _id: Auth.getCurrentUser()._id,
        name: Auth.getCurrentUser().name,
        department: Auth.getCurrentUser().department.name,
        role: Auth.getCurrentUser().role
      }
    };
    $scope.upload = function () {
      $upload.upload({
        url: '/api/shares', // upload.php script, node.js route, or servlet url
        method: 'POST',
        headers: {'Content-Type': 'multipart/form-data'}, // only for html5
        //withCredentials: true,
        data: currentProject,
        file: $scope.myFile // single file or a list of files. list is only for html5
        //fileName: 'doc.jpg' or ['1.jpg', '2.jpg', ...] // to modify the name of the file(s)
        //fileFormDataName: myFile, // file formData name ('Content-Disposition'), server side request form name
        // could be a list of names for multiple files (html5). Default is 'file'
        //formDataAppender: function(formData, key, val){}  // customize how data is added to the formData.
        // See #40#issuecomment-28612000 for sample code

      }).progress(function (evt) {
        $scope.progress = true;
        $scope.nowProgress = parseInt(100.0 * evt.loaded / evt.total) + '%';
        $scope.progressStatus = '上传中！';
        console.log('progress: ' + parseInt(100.0 * evt.loaded / evt.total) + '% file :'+ evt.config.file.name);
      }).success(function (data, status, headers, config) {
        // file is uploaded successfully
        $scope.progress = false;
        $scope.nowProgress = '0%';
        $scope.progressStatus = '上传成功！';
        console.log('file ' + config.file.name + 'is uploaded successfully. Response: ' + data);
        console.log(data);
      });
    }

    $scope.$on('$destroy', function () {
      socket.unsyncUpdates('share');
    });
  });
